package Semaphore_8;
import java.util.concurrent.Semaphore;
public class 多资源池_数据库连接池模拟 {
    private static final int POOL_SIZE = 5;
    private static final Semaphore available = new Semaphore(POOL_SIZE, true);
    private static int[] connections = new int[POOL_SIZE];

    static {
        for (int i = 0; i < POOL_SIZE; i++) {
            connections[i] = i; // 初始化连接ID
        }
    }

    public static void main(String[] args) {
        final int USER_COUNT = 20;

        for (int i = 0; i < USER_COUNT; i++) {
            final int userId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("用户-" + userId + " 等待获取数据库连接");
                        available.acquire();
                        int connId = getConnection();

                        System.out.println("用户-" + userId + " 获得连接[" + connId + "]");
                        Thread.sleep((long)(Math.random() * 1000 + 500)); // 模拟查询

                        releaseConnection(connId);
                        System.out.println("用户-" + userId + " 释放连接[" + connId + "]");
                        available.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private static synchronized int getConnection() {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (connections[i] != -1) {
                int connId = connections[i];
                connections[i] = -1; // 标记为已占用
                return connId;
            }
        }
        return -1; // 不会执行到这里，因为有Semaphore控制
    }

    private static synchronized void releaseConnection(int connId) {
        connections[connId] = connId; // 重置为可用
    }
}